package com.au.bescene.adapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

import com.au.bescene.R;
import com.au.bescene.util.PatchInputStream;

/**
 * Adapter for PhotoGallery.
 * @author Khaled
 *
 */
public class PhotoGalleryAdapter extends BaseAdapter {
	
	public static final int IMAGE_WIDTH = 150;
	public static final int IMAGE_HEIGHT = 100;
	
	private Context _context;
	private String _folderName;
	private ArrayList<String> _imageFileNames = new ArrayList<String>();
	ArrayList<Bitmap> _pictures = new ArrayList<Bitmap>();
	
	public PhotoGalleryAdapter(Context c, ArrayList<Bitmap> pictures, String folderName) {

		_pictures = pictures;
		_folderName = folderName;
		_context = c;
		
		setListOfFileNamesFromServer();
        
		
		TypedArray a = c
				.obtainStyledAttributes(R.styleable.default_gallery);
		a.getResourceId(
				R.styleable.default_gallery_android_galleryItemBackground,
				0);
		a.recycle();
	}

	/**
	 * Gets the list of photo galleries from BeScene server.
	 */
	private void setListOfFileNamesFromServer() {
		String result = "";
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(_context.getResources().getString(R.string.photogallery_script) + _folderName); 
		    HttpResponse response = httpclient.execute(httppost);
		    HttpEntity entity = response.getEntity();
		    InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		    StringBuilder sb = new StringBuilder();
		    String line = null;
		    
		    while ((line = reader.readLine()) != null) {
		    	sb.append(line + "\n");
		    }
		    
		    is.close();
		    result=sb.toString();
		} catch(Exception e) {
			Log.e("log_tag" , "Error converting result "+e.toString());
		}
	 
		try {
			JSONArray jArray = new JSONArray(result);
			
			
			for(int i = 2; i<jArray.length(); i++) {
				result="";
				result = jArray.getString(i);

				_imageFileNames.add(result);
			}

		} catch(JSONException e) {
			Log.e("log_tag", "Error parsing data "+e.toString());
		}
	}	

	public int getCount() {
		return _imageFileNames.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	/**
	 * Returns a new ImageView to be displayed, depending on the position
	 * passed.
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView i = new ImageView(_context);

		if (position >= _pictures.size()) {
			if (_imageFileNames.size() > 0) {
				try {
					URL aURL = new URL(_context.getResources().getString(
							R.string.photogalleryadapter_directoryofgalleries)
							+ _folderName + "/" + _imageFileNames.get(position));
					URLConnection conn = aURL.openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();

					PatchInputStream pis = new PatchInputStream(is);

					Bitmap bm = BitmapFactory.decodeStream(pis);
					pis.close();
					is.close();

					_pictures.add(bm);

					i.setImageBitmap((Bitmap) _pictures.get(position));

				} catch (IOException e) {
					Log.e("DEBUGTAG", "Remtoe Image Exception", e);
				}
			}
		}
		else
			i.setImageBitmap((Bitmap)_pictures.get(position));

		/* Image should be scaled as width/height are set. */
		i.setScaleType(ImageView.ScaleType.FIT_XY);
		/* Set the Width/Height of the ImageView. */
		i.setLayoutParams(new Gallery.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT));
		return i;
	}

	/**
	 * Returns the size (0.0f to 1.0f) of the views depending on the
	 * 'offset' to the center.
	 */
	public float getScale(boolean focused, int offset) {
		/* Formula: 1 / (2 ^ offset) */
		return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
	}

	public Bitmap getImageRessource(int position) {
		if(!_pictures.isEmpty())
			return (Bitmap)_pictures.get(position);
		else {
			getView(position, null, null);
			return getImageRessource(position);
		}
	}
}